/*
 * HttpWrapper.java
 *
 * Copyright (C) 2005-2006 Tommi Laukkanen
 * http://www.substanceofcode.com
 *
 * Created on June 6th 2005, 19:52
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */

package com.substanceofcode.carmanager.model;

import javax.microedition.io.*;
import java.io.*;
import java.util.Date;

/**
 * HttpWrapper is used when user wants to export data to email.
 * Exporting is done using the plain HTTP post to selected server.
 * Server's script will include the email creation code.
 *
 * @author  Tommi Laukkanen
 */
public class HttpWrapper {
    
    public boolean m_blnError;
    
    /**
     * Creates a new instance of HttpWrapper
     */
    public HttpWrapper() {
        m_blnError = false;
    }
    
    public String PostForm(String strURL, String strForm) throws IOException {
        m_blnError = false;
        HttpConnection c = null;
        
        InputStream is = null;
        StringBuffer bufBuffer = new StringBuffer();
        System.out.println("RawData: " + strForm);
        String type = "application/x-www-form-urlencoded";
        StringBuffer bufData = new StringBuffer();
        URLEncode(strForm, bufData);
        String encodedData = bufData.toString();  // user-supplied
        String strReturn = "";
        
        System.out.println("Creating secure connection");
        
        try {
            System.out.println("Open HTTP connector");
            
            c = (HttpConnection)Connector.open(strURL);
            
            System.out.println("Setting request parameters");
            
            c.setRequestMethod( HttpConnection.POST );
            c.setRequestProperty( "Content-Type", type );
            c.setRequestProperty( "Content-Length", String.valueOf( encodedData.length() ) );
            
            System.out.println("Opening output stream");
            
            OutputStream os = c.openOutputStream();
            os.write( encodedData.getBytes() );
            
            System.out.println("Wrote data to stream");
            
            // Getting the InputStream ensures that the connection
            // is opened (if it was not already handled by
            // Connector.open()) and the SSL handshake is exchanged,
            // and the HTTP response headers are read.
            // These are stored until requested.
            
            int intResponse = c.getResponseCode();
            System.out.println("HTTP Response code: " + intResponse);
            
//            System.out.println("Connecting... valvonta");
//             c = (HttpsConnection)Connector.open(url + "valvonta.asp");
//            System.out.println("Connected valvonta");
//            intResponse = c.getResponseCode();
//            System.out.println("HTTP Response code: " + intResponse);
            
            if( intResponse == HttpConnection.HTTP_OK) {
                is = c.openDataInputStream();
                
                System.out.println("OK");
                // Get the length and process the data
                int len = (int)c.getLength();
                if (len > 0) {
                    int ch;
                    for( int i=0; i<len; i++ ) {
                        if((ch = is.read()) != -1)
                            bufBuffer.append((char)ch);
                        //System.out.print( (char)ch );
                    }
                    byte[] data = new byte[len];
//                     int actual = is.readFully(data);
                } else {
                    int ch;
                    while ((ch = is.read()) != -1) {
                        bufBuffer.append((char)ch);
                        //System.out.print( (char)ch );
                    }
                }
                System.out.println("Buffer:\n" + bufBuffer.toString());
                strReturn = bufBuffer.toString();
            } else {
            }
        } catch(Exception ee) {
            m_blnError = true;
            strReturn = "Error: " + ee.toString();
            System.out.println("Error: " + ee.toString());
        } finally {
            if (is != null)
                is.close();
            if (c != null)
                c.close();
        }
        return strReturn;
    }
    
    public boolean getError() {
        return m_blnError;
    }
    
    public void URLEncode(String arg0, StringBuffer out) throws IOException {
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        DataOutputStream dOut = new DataOutputStream(bOut);
        dOut.writeUTF(arg0);
        ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray());
        bIn.read();
        bIn.read();
        int c = bIn.read();
        while (c >= 0) {
            if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '.' || c == '-' || c == '*' || c == '_')
                out.append((char) c);
            else if (c == ' ')
                out.append('+');
            else {
                if (c < 128) {
                    appendHex(c,out);
                } else if (c < 224) {
                    appendHex(c,out);
                    appendHex(bIn.read(),out);
                } else if (c < 240) {
                    appendHex(c,out);
                    appendHex(bIn.read(),out);
                    appendHex(bIn.read(),out);
                }
            }
            c = bIn.read();
        }
    }
    
    private void appendHex(int arg0, StringBuffer buff){
        buff.append('%');
        if (arg0<16)
            buff.append('0');
        buff.append(Integer.toHexString(arg0));
    }
    
}
